﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.IO;

namespace picasaDownloader
{
    public partial class frmPD : Form
    {
        public frmPD()
        {
            InitializeComponent();
        }

        IEnumerable<GoogleImages> imgs;

        private void btnLoadRSS_Click(object sender, EventArgs e)
        {
            try
            {
                Uri url = new Uri(tbRSSUrl.Text);



                //WebClient wc = new WebClient();
                //string rssXml = wc.DownloadString(url);
                XDocument rss = XDocument.Load(url.ToString());

                var urls = (
                    from node in rss.DescendantNodes()
                    where node.NodeType == System.Xml.XmlNodeType.Element && (node.ToString().StartsWith("<media:thumbnail") || node.ToString().StartsWith("<media:content"))
                    select (XElement)node
                        into el
                        select el.Attributes().First(n => n.Name == "url").Value).GroupBy(n => (new Uri(n)).Segments.Last());

                IEnumerable<GoogleImages> urlsN =
                    from el in urls
                    select new GoogleImages()
                    {
                        Name = el.Key,
                        Full = el.First(e2 => !Regex.IsMatch(e2, "/s\\d+/")),
                        Thumb =
                            from e2 in el
                            where Regex.IsMatch(e2, "/s\\d+/")
                            select new GoogleThumb() { TName = Regex.Match(e2, "/s\\d+/").ToString().Trim('/'), url = e2 }

                    };

                imgs = urlsN;
                cbThumb.DataSource = (from t in urlsN.First().Thumb
                                      select t.TName).ToList();
                //cbThumb.SelectedIndex = 1;
            }
            catch
            {
                MessageBox.Show("Some exception. Probably somthing wrong in url ;)");
            }
            


        }

        private void cbThumb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvImages.LargeImageList != null && lvImages.LargeImageList.Images != null)
                lvImages.LargeImageList.Images.Clear();
            lvImages.Items.Clear();
            var dt = from u in imgs
                       select new { Name = u.Name, Url = u.Full, Thumb = u.Thumb.First(t => t.TName == cbThumb.SelectedValue.ToString()).url };
            ImageList il = new ImageList();
            
            WebClient wc = new WebClient();
            foreach(var item in dt){
                if (File.Exists(Application.StartupPath + "\\th" + cbThumb.SelectedValue.ToString() + item.Name))
                    File.Delete(Application.StartupPath + "\\th" + cbThumb.SelectedValue.ToString() + item.Name);
                wc.DownloadFile(item.Thumb, Application.StartupPath + "\\th" + cbThumb.SelectedValue.ToString() + item.Name);
                Image im = Image.FromFile(Application.StartupPath + "\\th" + cbThumb.SelectedValue.ToString() + item.Name);
                if(il.ImageSize != im.Size)
                    il.ImageSize = im.Size;
                il.Images.Add(item.Name, im);
            }
            Size sz = new System.Drawing.Size(il.Images[0].Width, il.Images[0].Height);
            il.ImageSize = sz;
            //lvImages.LargeImageList.ImageSize = sz;
            lvImages.LargeImageList = il;
            //lvImages.StateImageList = il;
            foreach (var item in dt)
            {
                lvImages.Items.Add(new ListViewItem(item.Name, item.Name));
            }
        }

        private void btnDAll_Click(object sender, EventArgs e)
        {
            Download(imgs);
        }

        void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Download completed!");
        }

        private void btnDSelected_Click(object sender, EventArgs e)
        {
            List<string> sel = new List<string>();
            foreach(ListViewItem item in lvImages.SelectedItems)
            {
                sel.Add(item.Text);
            }
            var selected = from n in imgs
                           where sel.Contains(n.Name)
                           select n;

            Download(selected);
        }

        /// <summary>
        /// Downloads all images in the list.
        /// </summary>
        /// <param name="downloadList"></param>
        private void Download(IEnumerable<GoogleImages> downloadList)
        {
            WebClient wc = new WebClient();
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                foreach (var item in downloadList)
                {
                    wc = new WebClient();
                    wc.DownloadFileAsync(new Uri(item.Full), fbd.SelectedPath + "\\" + item.Name);
                }
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
            }
        }        
    }
}
